import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { nanoid } from 'nanoid';
import AvatarUpload from './avatarUpload';
import { Button, Col, Form, Input, message, Radio, Row, Spin } from 'antd';
import DraggableModal from '@/components/DraggableModal';
import DebounceWrapper from '@/components/DebounceWrapper';
import { fetchFileUrlById } from '@/services/common';
import { fetchAvailableDictChildList } from '@/services/system/dictionary';
import { addUser, modifyUser, checkUserName } from '@/services/system/user';
import { validatePhone, validateIdCard } from '@/utils/validate';

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const { Group } = Radio;
const { TextArea } = Input;
const DebounceButton = DebounceWrapper(Button);

export default ({ visible, options, closeModal, updateList }) => {
  const { userId, userDetailId } = options;
  const [form] = Form.useForm();
  const [initialLoading, setInitialLoading] = useState(true);
  const [userSexDict, setUserSexDict] = useState([]);
  const [userTypeDict, setUserTypeDict] = useState([]);
  const [userStatusDict, setUserStatusDict] = useState([]);
  const [actionLoading, setActionLoading] = useState(false);
  const [modifyInitLoadingId, setModifyInitLoadingId] = useState('');

  const formList = [
    {
      name: 'avatar',
      label: '用户头像',
      initialValue: null,
      rules: [],
      component: AvatarUpload,
      labelCol: { xs: { span: 6 }, md: { span: 3 } },
      wrapperCol: { xs: { span: 16 }, md: { span: 20 } },
      componentProps: {},
    },
    {
      name: 'userName',
      label: '用户账号',
      initialValue: '',
      validateTrigger: ['onChange', 'onBlur'],
      rules: [
        { required: true, whitespace: true, message: '请输入用户账号' },
        {
          validateTrigger: 'onBlur',
          validator: async (rule, val) => {
            if (val) {
              try {
                await checkUserName(_.assign(userId ? { id: userId } : {}, { userName: val }));
                return Promise.resolve();
              } catch (e) {
                return Promise.reject(new Error(e?.description || '重复校验不通过'));
              }
            }
            return Promise.resolve();
          },
        },
      ],
      component: Input,
      componentProps: {
        maxLength: 24,
        allowClear: true,
        placeholder: '请输入用户账号',
        autoComplete: 'off',
      },
    },
    {
      name: 'nickName',
      label: '用户昵称',
      initialValue: '',
      rules: [],
      component: Input,
      componentProps: {
        maxLength: 24,
        allowClear: true,
        placeholder: '请输入用户昵称',
        autoComplete: 'off',
      },
    },
    {
      name: 'realName',
      label: '用户姓名',
      initialValue: '',
      rules: [],
      component: Input,
      componentProps: {
        maxLength: 12,
        allowClear: true,
        placeholder: '请输入用户姓名',
        autoComplete: 'off',
      },
    },
    {
      name: 'identity',
      label: '用户身份证',
      initialValue: '',
      rules: [
        {
          validator: (rule, val) => {
            if (val && !validateIdCard(val)) {
              return Promise.reject(new Error('身份证格式校验不通过'));
            }
            return Promise.resolve();
          },
        },
      ],
      component: Input,
      componentProps: {
        maxLength: 18,
        allowClear: true,
        placeholder: '请输入用户身份证',
        autoComplete: 'off',
      },
    },
    {
      name: 'sex',
      label: '用户性别',
      initialValue: undefined,
      rules: [],
      component: Group,
      componentProps: {},
      componentChildren: userSexDict.map(({ value, label }) => (
        <Radio key={value} value={value}>
          {label}
        </Radio>
      )),
    },
    {
      name: 'staffId',
      label: '用户员工号',
      initialValue: '',
      rules: [],
      component: Input,
      componentProps: {
        maxLength: 24,
        allowClear: true,
        placeholder: '请输入用户员工号',
        autoComplete: 'off',
      },
    },
    {
      name: 'phone',
      label: '用户手机号',
      initialValue: '',
      rules: [
        {
          validator: (rule, val) => {
            if (val && !validatePhone(val)) {
              return Promise.reject(new Error('手机号校验不通过'));
            }
            return Promise.resolve();
          },
        },
      ],
      component: Input,
      componentProps: {
        maxLength: 11,
        allowClear: true,
        placeholder: '请输入用户手机号',
        autoComplete: 'off',
      },
    },
    {
      name: 'email',
      label: '用户邮箱',
      initialValue: '',
      rules: [],
      component: Input,
      componentProps: {
        maxLength: 36,
        allowClear: true,
        placeholder: '请输入用户邮箱',
        autoComplete: 'off',
      },
    },
    {
      name: 'userType',
      label: '用户类型',
      initialValue: undefined,
      rules: [{ required: true, message: '请选择用户类型' }],
      component: Group,
      componentProps: {},
      componentChildren: userTypeDict.map(({ value, label }) => (
        <Radio key={value} value={value} disabled={value !== '2'}>
          {label}
        </Radio>
      )),
    },
    {
      name: 'userStatus',
      label: '用户状态',
      initialValue: _.head(userStatusDict)?.value,
      rules: [{ required: true, message: '请选择用户状态' }],
      component: Group,
      componentProps: {},
      componentChildren: userStatusDict.map(({ value, label }) => (
        <Radio key={value} value={value}>
          {label}
        </Radio>
      )),
    },
    {
      name: 'remark',
      label: '备注',
      initialValue: '',
      rules: [],
      component: TextArea,
      labelCol: { xs: { span: 6 }, md: { span: 3 } },
      wrapperCol: { xs: { span: 16 }, md: { span: 20 } },
      componentProps: {
        showCount: true,
        maxLength: 128,
        autoSize: { minRows: 3, maxRows: 5 },
        placeholder: '请输入资源描述',
        autoComplete: 'off',
      },
    },
  ];

  // 获取字典数据
  const getDictData = async (dictType) => {
    try {
      const res = await fetchAvailableDictChildList({ dictType });
      return _.isArray(res)
        ? _.filter(
            _.map(res, ({ dictValue, dictLabel }) => ({ value: dictValue, label: dictLabel })),
            ({ value }) => _.isString(value) || _.isNumber(value),
          )
        : [];
    } catch (e) {
      return [];
    }
  };
  // 初始化
  useEffect(() => {
    Promise.all([getDictData('sex'), getDictData('user_type'), getDictData('user_Status')]).then(
      (result) => {
        const [sexDict, typeDict, statusDict] = result;
        setUserSexDict(sexDict);
        setUserTypeDict(typeDict);
        setUserStatusDict(statusDict);
        setInitialLoading(false);
      },
    );
  }, []);
  // 表单更新
  useEffect(() => {
    if (visible) {
      if (userId) {
        const { avatarPathId } = options;
        const defaultValue = _.pick(options, [
          'userName',
          'nickName',
          'phone',
          'userType',
          'userStatus',
          'realName',
          'identity',
          'staffId',
          'sex',
          'email',
          'remark',
        ]);
        if (avatarPathId) {
          const nextModifyInitLoadingId = nanoid(12);
          setModifyInitLoadingId(nextModifyInitLoadingId);
          fetchFileUrlById({ id: avatarPathId })
            .then((url) => {
              let validDataFetch;
              setModifyInitLoadingId((currentId) => {
                if (currentId === nextModifyInitLoadingId) {
                  validDataFetch = true;
                  return '';
                }
                return currentId;
              });
              if (validDataFetch && url) {
                defaultValue.avatar = [
                  {
                    url,
                    uid: nextModifyInitLoadingId,
                    name: 'avatar.png',
                    status: 'done',
                    fileId: avatarPathId,
                  },
                ];
                form.setFieldsValue(defaultValue);
              }
            })
            .catch(() => {
              let validDataFetch;
              setModifyInitLoadingId((currentId) => {
                if (currentId === nextModifyInitLoadingId) {
                  validDataFetch = true;
                  return '';
                }
                return currentId;
              });
              if (validDataFetch) {
                form.setFieldsValue(defaultValue);
              }
            });
        } else {
          form.setFieldsValue(defaultValue);
        }
      }
      return;
    }
    form.resetFields();
    setModifyInitLoadingId('');
  }, [visible]);

  const handleCancel = () => {
    if (!actionLoading) {
      closeModal();
    }
  };
  const handleConfirm = () => {
    setActionLoading(true);
    form
      .validateFields()
      .then((values) => {
        const [avatarFile] = values.avatar || [];
        const userInfoExtraDetail = _.assign(
          userDetailId ? { id: userDetailId } : {},
          _.pick(values, ['realName', 'identity', 'staffId', 'sex', 'email', 'remark']),
        );
        const params = _.assign(
          userId ? { id: userId } : {},
          avatarFile && avatarFile.fileId ? { avatarPathId: avatarFile.fileId } : {},
          _.pick(values, ['userName', 'nickName', 'phone', 'userType', 'userStatus']),
        );
        if (params.id) {
          params.userDetailInfoUpdateReqVo = userInfoExtraDetail;
        } else {
          params.userDetailInfoCreateReqVo = userInfoExtraDetail;
        }
        const confirmAction = params.id ? modifyUser : addUser;
        // console.log('params: ', params);
        confirmAction(params)
          .then(() => {
            closeModal();
            updateList && updateList();
            setActionLoading(false);
            message.success(`用户${params.id ? '修改' : '新增'}成功`);
          })
          .catch(() => {
            setActionLoading(false);
          });
      })
      .catch(() => {
        setActionLoading(false);
      });
  };

  return (
    <DraggableModal
      width={780}
      visible={visible}
      title={`用户${userId ? '编辑' : '添加'}`}
      onCancel={handleCancel}
      footer={[
        <DebounceButton key="cancel" disabled={actionLoading} onClick={closeModal}>
          取消
        </DebounceButton>,
        <DebounceButton
          key="confirm"
          type="primary"
          loading={actionLoading}
          onClick={handleConfirm}
        >
          提交
        </DebounceButton>,
      ]}
    >
      <Spin spinning={initialLoading || !!modifyInitLoadingId} tip={'初始化..'}>
        <Form {...layout} form={form} name="user-form">
          <Row>
            {formList.map((item, index) => (
              <Col
                xs={24}
                key={item.name}
                md={!index ? 24 : index === formList.length - 1 ? (index % 2 ? 24 : 12) : 12}
              >
                <Form.Item
                  {..._.pick(item, [
                    'name',
                    'label',
                    'tooltip',
                    'rules',
                    'initialValue',
                    'validateTrigger',
                    'labelCol',
                    'wrapperCol',
                  ])}
                >
                  {item.component
                    ? React.createElement(
                        item.component,
                        { ...item.componentProps },
                        item.componentChildren,
                      )
                    : null}
                </Form.Item>
              </Col>
            ))}
          </Row>
        </Form>
      </Spin>
    </DraggableModal>
  );
};
